Skip to content

fix: harden Paykit request handling - #684

Open
ben-kaufman wants to merge 10 commits into
masterfrom
codex/paykit-request-qa-fixes
Open

fix: harden Paykit request handling#684
ben-kaufman wants to merge 10 commits into
masterfrom
codex/paykit-request-qa-fixes

Conversation

@ben-kaufman

@ben-kaufman ben-kaufman commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

This PR hardens incoming Paykit contact-payment handling after QA on the cross-platform payment-request flow.

Description

  1. Keeps one contact's malformed private receiver marker from blocking endpoint publication for otherwise valid contacts, while continuing to reject the malformed marker itself.
  2. Validates incoming request amounts during initial invoice routing, so unaffordable requests show the standard insufficient Spending or Savings balance message instead of reaching coin selection with a generic error.

No Paykit SDK or binding change is required. Companion Android fix: synonymdev/bitkit-android#1172

Linked Issues/Tasks

Screenshot / Video

N/A — this corrects error handling in the existing payment-request flow.

QA Notes

Manual Tests

  • 1. Saved contacts include one malformed remote Paykit marker → enable Contact Payments: valid contacts publish their private payment details and the malformed marker remains unusable.
  • 2a. Incoming LN payment request exceeds Spending balance → open request: the insufficient Spending message appears instead of coin selection.
    • 2b. Incoming on-chain payment request exceeds Savings balance → open request: the insufficient Savings message appears instead of coin selection.

Automated Checks

  • PrivatePaykitServiceTests: 15 tests passed on an iPhone 16 simulator.
  • The Debug simulator test build, SwiftFormat lint, and git diff --check passed.

@greptile-apps

greptile-apps Bot commented Aug 26, 2026

Copy link
Copy Markdown

Greptile Summary

This PR hardens incoming Paykit contact-payment handling by isolating malformed receiver markers and validating request amounts against the balance before entering the send flow.

  • Allows valid contacts’ private endpoints to publish when another contact has a malformed receiver marker.
  • Uses the incoming Paykit request amount for Lightning and on-chain preflight balance checks.
  • Adds a changelog entry describing the corrected behavior.

Confidence Score: 5/5

The PR appears safe to merge, with the changed preflight checks aligned to the amount ultimately paid and malformed markers safely isolated from valid contacts.

Private Paykit endpoints are intentionally amountless, the incoming request amount is injected into payment execution and checked again during confirmation, and valid receiver paths continue through publication while malformed paths remain rejected and logged.

Important Files Changed

Filename Overview
Bitkit/Services/PrivatePaykitService+Contacts.swift Stops a malformed receiver marker from becoming the aggregate publication error while retaining logging and processing valid receiver paths.
Bitkit/ViewModels/AppViewModel.swift Uses the incoming request amount for initial Lightning and on-chain affordability checks, matching the amount later injected into payment execution.
changelog.d/next/paykit-request-qa.fixed.md Accurately documents the malformed-marker isolation and insufficient-balance handling fixes.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Incoming Paykit request] --> B[Resolve private amountless endpoint]
  B --> C[Decode Lightning, on-chain, or unified target]
  C --> D[Read amount from incoming request]
  D --> E{Preferred route has sufficient balance?}
  E -->|Yes| F[Open shared send flow]
  E -->|No, unified request| G{On-chain balance sufficient?}
  G -->|Yes| F
  G -->|No| H[Show insufficient balance message]
  E -->|No, single route| H
  F --> I[Inject request amount]
  I --> J[Confirm exact request amount]
  J --> K[Pay]
Loading

Reviews (1): Last reviewed commit: "fix: harden Paykit contact payments" | Re-trigger Greptile

@piotr-iohk

piotr-iohk commented Aug 27, 2026

Copy link
Copy Markdown
Collaborator

Retested after 97033fe.

Enable — still fails. ❌

Toggle Enable payments with contactsPrivate Paykit is not available, toggle does not stay on. Same staging contact as the Android QA (pubky1jy146y751hkgqk9p69ds5cqf461aj5x7c8ptbca5rw6m9asotso). Recording + logs attached.

This is not the malformed-marker isolation path. enable() still calls preparePrivateEndpoints(..., requireImmediate: true) before setting publishingEnabledKey. canPublishPrivateEndpoints requires that flag already true, so any saved contact fail-closes as privateUnavailable.

Same surface on Android #1172 (toast there is Unknown error).

Steps:

  1. Paykit UI on. Profile exists. Staging pubky above saved as a contact (need not be live).
  2. Payments with contacts off.
  3. Enable payments with contacts.
  4. Toast is Private Paykit is not available; toggle stays off.
Screen.Recording.2026-08-27.at.10.25.35.-.ios.mov

bitkit_logs_2026-08-27_08-28-24.zip

Over-balance — copy is fixed, toast loops. ❌

Pay on a request larger than the wallet now shows the right message (Insufficient Savings, e.g. ₿ 26,717 more needed) instead of coin selection. On Android that toast fires once. On iOS it keeps coming back. Tapping Pay again then shows The payment request is already being processed. Recording attached.

validateOnchainBalance toasts and returns; presentNextIncomingPaykitPaymentRequest then deferPresentation (2s × 14). Each retry runs handleScannedData again and toasts again. Android’s equivalent is clearActiveContactPaymentContext(retryIncomingRequest = false) after the insufficient toast — no retry.

Steps:

  1. Two live wallets, payments with contacts on. Payer under the request amount (split savings + spending is fine).
  2. Other wallet requests more than that total.
  3. On iOS, tap Pay on the incoming request / See All row.
  4. Insufficient Savings toast repeats. A second Pay can show already being processed.
Screen.Recording.2026-08-27.at.11.14.21-os.overbalance.mov

bitkit_logs_2026-08-27_09-15-42-overbalance.zip

@ben-kaufman

Copy link
Copy Markdown
Contributor Author

Fixed both retest findings in 5ba7ee7. Private publication is now enabled before immediate endpoint preparation, with rollback still handled by the existing failure path. An unaffordable request is marked surfaced after the single balance toast, so it remains in the bell/history queue without the 2-second automatic retry loop or already-processing follow-up. The focused iOS suites pass 56/56 tests.

@ben-kaufman
ben-kaufman requested a review from ovitrif August 31, 2026 18:00

@ovitrif ovitrif left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The unaffordable incoming request path and the malformed-marker isolation both lack tests that would fail if those behaviors regressed.

  1. handleScannedData now uses incomingPaymentRequest.amountSats and the insufficient-balance path marks the request presented so it does not retry. No test drives an unaffordable request through that routing.
  2. A malformed private receiver marker no longer assigns firstError, so other contacts can still publish. No fixture would fail if that assignment returned.

Inline comments have the specific coverage to add.

Comment thread Bitkit/ViewModels/AppViewModel.swift
Comment thread Bitkit/Services/PrivatePaykitService+Contacts.swift
@ben-kaufman
ben-kaufman requested a review from ovitrif August 31, 2026 22:41
@piotr-iohk

Copy link
Copy Markdown
Collaborator

Retested 112fb70.

Over-balance: fixed. One insufficient-capacity toast, no retry loop. ✅

Enable: still broken. Five toggles failed with privateUnavailable ❌
(09:41:49, 09:41:57, 09:46:04, 09:46:17, 09:46:25). Setting
publishingEnabledKey first did not help.

Logs never reach inspect/prepare/queue/deliver. 09:46:04 is
pubky_secret_key loaded → enable ERROR in 2ms, so this is still
canPublishPrivateEndpoints == false + requireImmediate + a saved
contact, then restore() rolls the toggle off.

Also still had pubky8u997gg after deleting pubky1jy146y, so this
is not specific to that staging contact.

Need the failing canPublish clause logged, and enable should not
fail-close when publication never actually ran.

Screen.Recording.2026-09-01.at.11.58.31.mov

bitkit_logs_2026-09-01_09-46-59.zip

@ben-kaufman
ben-kaufman force-pushed the codex/paykit-request-qa-fixes branch from 112fb70 to 154b3d6 Compare September 1, 2026 12:32
@ben-kaufman

Copy link
Copy Markdown
Contributor Author

Fixed the remaining enable failure in 2d90e0e. Private endpoint preparation during enable is now best effort, so temporary wallet, node, app, or Pubky unreadiness defers publication instead of returning privateUnavailable and rolling the toggle back. Real errors after publication starts still fail and restore the previous state. The readiness check now logs the exact unavailable condition. ContactPaymentsServiceTests and PrivatePaykitServiceTests pass 24 of 24. @piotr-iohk please retest the Enable case, and @ovitrif please re-review the updated head.

@piotr-iohk

piotr-iohk commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator

Retested latest revision (2d90e0e), iPhone 17 sim.

Enable still fail-closes. Toggle → Failed to update contact payments: privateUnavailable (GeneralSettingsView.updateContactPayments line 180) → “Private Paykit is not available.”

2d90e0e is on this build — startup logged Deferring private Paykit endpoint publication during prepare: private publication is disabled (flag off, 0 contacts). On the enable attempt itself there was no second defer: flag was set, canPublish passed, then it still threw. Sequence: loaded 1 contact (pubkypwuhkhj…), then the error ~11s later. No Failed to inspect/prepare/sync WARN around the fail.

Hypothesis: requireImmediatePublication: false on enable is bypassed by the unguarded return error after receiverPathSelection in syncLocalEndpointPublicationLocked. Other failures on that path are supposed to defer.

Android enable stays on after the matching defer change.

Logs:
bitkit_logs_2026-09-01_15-09-55.zip

@ben-kaufman

Copy link
Copy Markdown
Contributor Author

You were right about the remaining fail-closed path. The receiverPathSelection catch returned immediately before the deferred-publication policy was applied. Signed commit ab3308b8 now records/logs that per-contact error, continues reconciliation, and returns it only for immediate publication.

The regression test covers this exact selection failure, and the focused private/contact/request suites pass 74/74. I also installed this exact head over the saved-contact QA state, enabled Paykit UI, and verified the toggle stayed enabled past 15 seconds with the success toast and no privateUnavailable rollback. Please retest ab3308b8 after the fresh checks finish.

ovitrif
ovitrif previously approved these changes Sep 1, 2026

@ovitrif ovitrif left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

utACK

@piotr-iohk

piotr-iohk commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator

Retested ab3308b on latest local head. Enable/disable with the same staging contact (pubky1jy146y751hkgqk9p69ds5cqf461aj5x7c8ptbca5rw6m9asotso) still showed Private Paykit is not available. and the toggle did not stay off. Android does not toast and the switch turns off.

Same privateUnavailable on both platforms (cleanup/delivery to that contact fails). Android defers private cleanup and keeps the toggle off. iOS was still throwing from disable(), toasting, and restoring the previous on state.

I brought the Android disable logic over in 9104ff4: failed private cleanup now marks cleanup pending and succeeds the toggle. After that change the toast is gone and the switch stays off. Public cleanup still fail-closes.

@ben-kaufman @ovitrif please review if this makes sense.

Before (ab3308b)

ios on the left:

Screen.Recording.2026-09-02.at.08.59.47-trim-before.mov

After (9104ff4)

Screen.Recording.2026-09-02.at.09.21.14-after.mov

piotr-iohk
piotr-iohk previously approved these changes Sep 2, 2026
ovitrif
ovitrif previously approved these changes Sep 2, 2026

@ovitrif ovitrif left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

utACK

@jvsena42 jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review of the branch diff (origin/master...HEAD), skipping anything already raised in the existing threads. Four findings, all inline below. The two Paykit ones share a root cause: handleUnavailablePaymentRoute swapped deferPresentation (which always bumps presentationGeneration) for markPresentedIfPending (which bumps it only for user-requested presentations).

🤖 Generated with Claude Code

Comment thread Bitkit/AppScene.swift
Comment thread Bitkit/Services/PaykitPaymentRequestService.swift
Comment thread Bitkit/Services/ContactPaymentsService.swift
Comment thread Bitkit/Services/ContactPaymentsService.swift
@ben-kaufman
ben-kaufman dismissed stale reviews from ovitrif and piotr-iohk via dfffd98 September 4, 2026 12:24
@ben-kaufman
ben-kaufman force-pushed the codex/paykit-request-qa-fixes branch from 3f260b5 to dfffd98 Compare September 4, 2026 12:24
@ben-kaufman
ben-kaufman force-pushed the codex/paykit-request-qa-fixes branch from dfffd98 to b416f6f Compare September 4, 2026 16:31

@jvsena42 jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Second review pass. Confirmed fixed since the last round: the AppScene presentation-loop termination and the publishingEnabledKey ordering. The other two were declined as intentional, so I'm not re-raising them.

Two new findings below, both fallout from the fix for the ordering issue and the decision to keep disable() swallowing removal failures.

Comment thread Bitkit/Services/ContactPaymentsService.swift Outdated
Comment thread Bitkit/Services/ContactPaymentsService.swift Outdated
@ben-kaufman
ben-kaufman requested a review from jvsena42 September 4, 2026 17:25

@jvsena42 jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Third pass, on 06901046. Both findings from the previous review are fixed: requireImmediatePublication is back to true with the deferral narrowed to the privateEndpointPublicationUnavailabilityReason check, and the malformed-marker isolation survives that restoration, so the original QA fix still holds.

Two new findings below. One note for the record, not filed as a finding: enable() now silently succeeds when the unavailability reason is "the app is not active" or "the Lightning node is not running", leaving the toggle on with nothing published — that self-heals via startInitialLinkBurst, and it reads as the deliberate trade-off this fix chose over failing closed.

Comment thread Bitkit/Services/ContactPaymentsService.swift
Comment thread BitkitTests/PrivatePaykitServiceTests.swift

@jvsena42 jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked each hardening against what it claims to close. The amount the user sees is the amount paid — validateIncomingPaymentRequestAmounts fails closed on any request/invoice/bolt11-msat disagreement — and the request gate matches Android for asset, bounds, role/state, expiry and network-filtered identifiers. No funds or auth issue.

Two hardenings are half-closed; both are low because the second line of defence holds. I dropped a third finding about publication error handling: @ovitrif already raised it and the answer plus its test are in this PR.

Comment thread Bitkit/ViewModels/AppViewModel.swift
Comment thread Bitkit/ViewModels/AppViewModel.swift
@ben-kaufman
ben-kaufman requested a review from jvsena42 September 4, 2026 21:52

@ovitrif ovitrif left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

QA Notes

Tested on an iPhone 17 simulator (iOS 26.5) on regtest, against a build of this branch verified by symbol.

  • 2b passed. An on-chain request for 500,000 sats against a zero Savings balance showed the InsufficientSavingsToast with the amount still needed, and the flow stayed on the recipient screen instead of continuing into coin selection.
  • 2a not run. The only BOLT11 fixture in Docs/SCAN_INVOICE_TEST_MATRIX.md has expired, and expiry is checked before the balance check, so the scan stops at This Lightning invoice has expired and never reaches the spending comparison. That fixture is stale test data rather than anything wrong here, but it does mean the Lightning half of this claim is still unverified on device. Could we refresh that fixture, or note in the doc that it needs regenerating against a live regtest peer?
  • 1 not run. A malformed remote receiver marker lives on the counterparty's Pubky homeserver, so reproducing it needs a second Pubky identity publishing the bad marker. PrivatePaykitServiceTests covers this through the injected EndpointPublicationOperations seam.

One thing worth recording for whoever retests: the toast 2b exercises comes from validateOnchainBalance, which every scan path shares. A plain bitcoin: or lightning: link leaves contactPaymentContext nil, so the new acceptsLightningInvoiceAmount guards and the handleUnavailablePaymentRoute suppression are not on that path. Confirming the request-specific behaviour, that an unaffordable request stops re-presenting itself but stays payable from PaymentRequestsView, needs a real incoming request from a second identity.

The code review is clean. The isolation in prepareSavedContacts keeps a failed receiver path out of receiverPathsForPrivateEndpointCleanup so a malformed marker no longer blocks healthy contacts, and the coarser acceptsLightningInvoiceAmount(satoshis:) pre-routing gate is safe because validateIncomingPaymentRequestAmounts still runs the exact msat cross-check before every send.

Approve.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants